import json
import os
import time

from .leetcode_operation import LeetCodeOperation


class SubmissionList(LeetCodeOperation):
    def __init__(self, requests_manager, base_url="https://leetcode.cn", **params):
        super().__init__(requests_manager, base_url)
        self.params = params.get('params')
        self.filename = "submission_list.json"
        self.endpoint = 'graphql'

    def generate_payload(self):
        query_string = "\n    query submissionList($offset: Int!, $limit: Int!, $lastKey: String, $questionSlug: String!, $lang: String, $status: SubmissionStatusEnum) {\n  submissionList(\n    offset: $offset\n    limit: $limit\n    lastKey: $lastKey\n    questionSlug: $questionSlug\n    lang: $lang\n    status: $status\n  ) {\n    lastKey\n    hasNext\n    submissions {\n      id\n      title\n      status\n      statusDisplay\n      lang\n      langName: langVerboseName\n      runtime\n      timestamp\n      url\n      isPending\n      memory\n      submissionComment {\n        comment\n        flagType\n      }\n    }\n  }\n}\n    "
        return {
            "query": query_string,
            "variables": self.params,
            "operationName": "submissionList"
        }

    def parse_graphql_data(self, data):
        submissions_data = data.get('data', {}).get('submissionList', {})
        parsed_submissions = {
            'lastKey': submissions_data.get('lastKey'),
            'hasNext': submissions_data.get('hasNext'),
            'submissions': []
        }
        submissions = submissions_data.get('submissions', [])
        if not submissions:
            return {}
        
        for submission in submissions:
            parsed_submission = {
                'id': submission.get('id'),
                'title': submission.get('title'),
                'status': submission.get('status'),
                'statusDisplay': submission.get('statusDisplay'),
                'lang': submission.get('lang'),
                'langName': submission.get('langName'),  # Originally 'langVerboseName'
                'runtime': submission.get('runtime'),
                'timestamp': submission.get('timestamp'),
                'url': submission.get('url')
                # Add other fields as necessary
            }
            parsed_submissions['submissions'].append(parsed_submission)

        return parsed_submissions

    def fetch_all_data(self, folder_path="SubmissionList", request_interval=1):
        submission_folder = "Submission"
        
        os.makedirs(os.path.join(self.directory, folder_path), exist_ok=True)
        slugs = [filename.split('.')[0] for filename in  os.listdir(os.path.join(self.directory, submission_folder))]

        for slug in slugs:
            self.logger.info(f"slug: {slug}")
            self.params.update({'questionSlug': slug})
            file_path = os.path.join(folder_path, f"{slug}.json")
            
            if os.path.exists(os.path.join(self.directory, file_path)):
                continue
            
            data = self.fetch_data(self.endpoint, method='POST')
            parsed_data = self.parse_graphql_data(data)

            if parsed_data.get('submissions'):
                self.save_json(parsed_data, file_path)
            
            time.sleep(request_interval)

    def execute(self):
        data = self.fetch_data(self.endpoint, method='POST')
        parsed_data = self.parse_graphql_data(data)
        self.save_json(parsed_data, self.filename)
